package com.miao.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.miao.common.entity.Message;
import com.miao.common.service.ChatService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author MiaoWenqing
 * @description: 聊天服务层 实现
 * @date 2021/2/4 15:01
 */
@Service
public class ChatServiceImpl implements ChatService {


    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取 聊天记录
     * @param uid 用户id
     * @param storeId 店铺id
     * @return list
     */
    @Override
    public List<Message> getMessageRecord(String uid, String storeId) {
        String records = (String) this.redisTemplate.opsForHash().get("chat:record", storeId + ":" + uid);
        return JSON.parseArray(records, Message.class);
    }

    @Override
    public boolean saveMessageRecord(Message message) {



          message.setSendTime(new Date());
        System.out.println(message.toString());
        List<Message> messageRecord;
        if (message.getType().equals("1")){
            //客服发送的消息
            messageRecord = this.getMessageRecord(message.getReceiveId(), message.getStoreId());
            if (null==messageRecord){
                messageRecord=new ArrayList<Message>();
            }
            messageRecord.add(message);
            this.redisTemplate.opsForHash().put("chat:record",message.getStoreId()+":"+message.getReceiveId(),JSON.toJSONString(messageRecord));
        }else {
            //顾客发送的消息
            messageRecord = this.getMessageRecord(message.getSendId(), message.getStoreId());
            if (null==messageRecord){
                messageRecord=new ArrayList<Message>();
            }
            messageRecord.add(message);
            this.redisTemplate.opsForHash().put("chat:record",message.getStoreId()+":"+message.getSendId(),JSON.toJSONString(messageRecord));
        }
        return true;
    }

    /**
     * 创建会话
     *
     * @param storeId 客服id
     * @param uid      顾客id
     */
    @Override
    public void creatSession(String storeId, String uid,String waiterId) {
        this.redisTemplate.opsForHash().put("chat:session",storeId+":"+uid,waiterId);
    }

    /**
     * 关闭会话
     *
     * @param storeId 客服id
     * @param uid      顾客id
     */
    @Override
    public void closeSession(String storeId, String uid) {
         this.redisTemplate.opsForHash().delete("chat:session",storeId+":"+uid);
    }

    /**
     * 客服上线
     *
     * @param storeId  店铺id
     * @param waiterId 客服id
     */
    @Override
    public void onlineWaiter(String storeId, String waiterId) {
        this.redisTemplate.opsForList().leftPush("chat:waiter:" + storeId, waiterId);
    }

    /**
     * 客服下线
     *
     * @param storeId  店铺id
     * @param waiterId 客服id
     */
    @Override
    public void outlineWaiter(String storeId, String waiterId) {
        this.redisTemplate.opsForList().remove("chat:waiter:" + storeId, 10, waiterId);
    }

    /**
     * 客户加入等待队列
     *
     * @param storeId 店铺id
     * @param uid     客户id
     */
    @Override
    public void pushWaitQueue(String storeId, String uid) {
        this.redisTemplate.opsForList().leftPush("chat:wait:" + storeId, uid);
    }

    /**
     * 客户出等待队列
     *
     * @param storeId 店铺id
     * @param uid     客户
     */
    @Override
    public void popWaitQueue(String storeId, String uid) {
        this.redisTemplate.opsForList().remove("chat:wait:" + storeId, 10, uid);
    }

    /**
     * 店铺全部等待用户
     *
     * @param storeId 店铺id
     * @return list
     */
    @Override
    public List<Object> waitQueue(String storeId) {


        return  this.redisTemplate.opsForList().range("chat:wait:"+storeId,0 ,-1);
    }

    /**
     * 随机匹配客服
     *
     * @param storeId 店铺ID
     * @return int
     */
    @Override
    public long matchWaiter(String storeId) {
        Long size = this.redisTemplate.opsForList().size("chat:waiter:"+storeId);
        if (null!=size){
            return  size;
        }
        return  0;
    }

    /**
     * 获取客服id
     *
     * @param index 下标
     * @return id
     */
    @Override
    public String getWaiterId(String storeId ,long index) {

        return (String) this.redisTemplate.opsForList().index("chat:waiter:"+storeId, index);
    }

    /**
     * 机器人客服
     *
     * @param context 消息内容
     * @return 回答语句
     */
    @Override
    public String robotWaiter(String context) {


        /**
         * ============================图灵机器人==========================
         */
//
//        try {
//
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            HttpPost httpPost = new HttpPost("http://openapi.tuling123.com/openapi/api/v2");
//            String entity="{\n" +
//                    "\t\"reqType\": 0,\n" +
//                    "\t\"perception\": {\n" +
//                    "\t\t\"inputText\": {\n" +
//                    "\t\t\t\"text\": \""+context+"\"\n" +
//                    "\t\t}\n" +
//                    "\t},\n" +
//                    "\t\"userInfo\": {\n" +
//                    "\t\t\"apiKey\": \"65bb28f90a4a40fe8cc86417801b9c9a\",\n" +
//                    "\t\t\"userId\": \"433707\"\n" +
//                    "\t}\n" +
//                    "}";
//            StringEntity se = new StringEntity(entity, "UTF-8");
//            se.setContentType("application/json");
//            httpPost.setEntity(se);
//            CloseableHttpResponse response = httpClient.execute(httpPost);
//            HttpEntity entity1 = response.getEntity();
//            String resStr = null;
//            if (entity1 != null) {
//                resStr = EntityUtils.toString(entity1, "UTF-8");
//            }
//            httpClient.close();
//            response.close();
//
//            Map map = JSON.parseObject(resStr, Map.class);
//            Object results = map.get("results");
//            String string1 = JSON.toJSONString(results);
//            List<String> strings = JSON.parseArray(string1, String.class);
//            for (String s : strings) {
//                Map map1 = JSON.parseObject(s, Map.class);
//                if (map1.get("resultType").equals("text")) {
//                    String string2 = JSON.toJSONString(map1.get("values"));
//                    Map map2 = JSON.parseObject(string2, Map.class);
//
//
//                    if (map2.get("text").toString().equals("请求次数超限制!")){
//                        return "😊";
//                    }else {
//                        return  map2.get("text").toString();
//                    }
//
//                }
//            }
//            return "😊";
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "😊";
//        }
        /**
         * ============================百度智能问答==========================
         */
        String path = "https://jisuapiareacode.api.bdymkt.com/iqa/query";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials("56d6790c95564375b326f3034ed0c753", "cdde6ac54aeb4478ac5d89cf0da2f1e8");

        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

        request.addQueryParameter("question", context);



        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串


            Map map = JSON.parseObject(response.getResult(), Map.class);
            if (map.get("msg").equals("ok")) {
                Object result = map.get("result");
                String string1 = JSON.toJSONString(result);
                Map map1 = JSON.parseObject(string1, Map.class);

                if( map1.get("content").toString().equals("defaultReply")){
                    return  "😊 我累了，不想回答你";
                }
                return  map1.get("content").toString().replaceAll("小i机器人","本店");
            }
            return  "😊";
        } catch (Exception e) {
            e.printStackTrace();
            return "😊";
        }
    }
}
